package cat.joronya.supermanager.europeo.service;

import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.htmlcleaner.ContentNode;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;

import android.util.Log;
import cat.joronya.supermanager.europeo.Supermanager;
import cat.joronya.supermanager.europeo.team.Team;

/**
 * Donat l'HTML del llistat d'equips, el parsejem i
 * retornem els equips en VO's.
 * 
 * @author pol
 */
public class MyTeamParser 
{
	private static final String TAG = "supermanager";

	// teams XPATH
	private static final String TEAMS_XPATH = "//td[@background='gif/tusequipos2.gif']";

	// jornada XPATH
	private static final String TEAMS_DAY_XPATH = "//td[@class='gris']";

	/**
	 * retorna els equips parsejats del HTML passat.
	 */
	@SuppressWarnings("rawtypes")
	public ArrayList<Team> parse(String html) throws Exception
	{
		ArrayList<Team> teams = new ArrayList<Team>();

		HtmlCleaner cleaner = new HtmlCleaner();
		TagNode node = cleaner.clean(html);

		NumberFormat nf = NumberFormat.getInstance(new Locale("es","ES"));

		// cerquem els equips
		Object[] tdTeam = node.evaluateXPath(TEAMS_XPATH);
		TagNode tagTeamHeader = (TagNode)tdTeam[0];
		TagNode tagTeamTable = tagTeamHeader.getParent().getParent();

		// trs, per saber si hi ha algun equip
		List trs = tagTeamTable.getChildren();
		if( trs.size() > 3 )
		{
			// llistem els equips, diferents trs
			for(Object objTr: trs)
			{
				// els tds
				List tds = ((TagNode)objTr).getChildren();

				// primer td
				TagNode td0 = (TagNode)tds.toArray()[0];

				// si es el primer acabem, es a dir te background='gif/tusequipos2.gif'
				if( "gif/tusequipos2.gif".equals(td0.getAttributeByName("background")) )
					continue;

				// si tenim equips inacabats, apareix fila amb missatge, amb colspan=6
				if( "6".equals(td0.getAttributeByName("colspan")) )
					continue;
				
				// si es l'ultim acabem, es a dir te background='gif/tusequiposabajo2.gif'
				if( "gif/tusequiposabajo2.gif".equals(td0.getAttributeByName("background")) )
					continue;

				// segon td
				TagNode td1 = (TagNode)tds.toArray()[1];

				// agafem fills a veure si es equip
				List td1Childs = td1.getChildren();

				// tr de titols pq td1 amb un fill, el br i no img i anchor
				if( td1Childs.size() == 1 )
					continue;

				TagNode td1ChildsChild1 = (TagNode)td1Childs.toArray()[1];

				// inicialitzem team
				Team team = new Team();
				// cerquem nom de l'equip
				if( "a".equals(td1ChildsChild1.getName()) )
				{
					String href = td1ChildsChild1.getAttributeByName("href");
					String id_equ = href.replaceFirst("verequipo.php.id_equ=", "");
					team.setIdEqu(id_equ);
					for( Object aContent: td1ChildsChild1.getChildren() )
					{
						if( aContent instanceof ContentNode )
							team.setName(aContent.toString());
					}
				}

				// tenim creu roja, semafor o 10jug?
				if( td1Childs.size() > 3 )
				{
					// el 3er fill pq hi ha un salt de linia en ContentNode
					TagNode td1ChildsChild2 = (TagNode)td1Childs.toArray()[3];

					// lesio o semafor
					if( "img".equals(td1ChildsChild2.getName()) )
					{
						String src = td1ChildsChild2.getAttributeByName("src");
						String alt = td1ChildsChild2.getAttributeByName("alt");

						// lesio
						if( "gif/lesion.gif".equals(src) )
						{
							team.setStatus(Supermanager.MyTeam.STATUS_LESIONAT);
							alt = alt.replace(" jugador lesionado", "");
							alt = alt.replace(" jugadores lesionados", "");
							try
							{
								team.setTeamPlayers(new Integer(alt));
							}catch(Exception e)
							{}
						}
						// altrament descartat
						else if( "gif/baja.gif".equals(src) )
						{
							team.setStatus(Supermanager.MyTeam.STATUS_DESCARTAT);
							// TODO: parse number of descarted players
						}
					}

					// 10 jugadors
					if("font".equals(td1ChildsChild2.getName()) )
					{
						List fontChildren = td1ChildsChild2.getChildren();
						ContentNode fontContent = (ContentNode)fontChildren.get(0);
						String teamPlayers = fontContent.toString();
						teamPlayers = teamPlayers.replace("(", "");
						teamPlayers = teamPlayers.replace(" jug.)", "");
						team.setStatus(Supermanager.MyTeam.STATUS_INCOMPLETE_TEAM);
						try
						{
							team.setTeamPlayers(new Integer(teamPlayers));
						}catch(Exception e)
						{}
					}
				}

				// tercer td
				TagNode td2 = (TagNode)tds.toArray()[2];
				for( Object td2Child: td2.getChildren() )
				{
					if( td2Child instanceof ContentNode )
					{
						Float points = Float.valueOf("0");
						Integer pointsClass = Integer.valueOf(0);
						Pattern p = Pattern.compile("([^\\s]*)\\s\\(([^\\º]*)º\\)");
						Matcher m = p.matcher(td2Child.toString());
						if( m.find() ) 
						{
							try{
								points = Float.valueOf(nf.parse(m.group(1)).floatValue());
							}catch(ParseException pe){
								points = Float.valueOf("0");
							}
							try{
								pointsClass = Integer.valueOf(nf.parse(m.group(2)).intValue());
							}catch(ParseException pe){
								pointsClass = Integer.valueOf("0");
							}
						}
						team.setPoints(points);
						team.setPointsClassification(pointsClass);
					}
				}

				// quart td
				TagNode td3 = (TagNode)tds.toArray()[3];
				for( Object td3Child: td3.getChildren() )
				{
					if( td3Child instanceof ContentNode )
					{
						Float general = Float.valueOf("0");
						Integer generalClass = Integer.valueOf(0);
						Pattern p = Pattern.compile("([^\\s]*)\\s\\(([^º]*)º\\)");
						Matcher m = p.matcher(td3Child.toString());
						if( m.find() ) 
						{
							try{
								general = Float.valueOf(nf.parse(m.group(1)).floatValue());
							}catch(ParseException pe){
								general = Float.valueOf("0");
							}
							try{
								generalClass = Integer.valueOf(nf.parse(m.group(2)).intValue());
							}catch(ParseException pe){
								generalClass = Integer.valueOf("0");
							}
						}
						team.setGeneral(general);
						team.setGeneralClassification(generalClass);
					}
				}

				// cinque td
				TagNode td4 = (TagNode)tds.toArray()[4];
				for( Object td4Child: td4.getChildren() )
				{
					if( td4Child instanceof ContentNode )
					{
						Integer broker = Integer.valueOf("0");
						Integer brokerClass = Integer.valueOf(0);
						Pattern p = Pattern.compile("([^\\s]*)\\s*\\(([^º]*)º\\)");
						Matcher m = p.matcher(td4Child.toString());
						if( m.find() ) 
						{
							try{
								broker = Integer.valueOf(nf.parse(m.group(1)).intValue());
							}catch(ParseException pe){
								broker = Integer.valueOf("0");
							}
							try{
								brokerClass = Integer.valueOf(nf.parse(m.group(2)).intValue());
							}catch(ParseException pe){
								brokerClass = Integer.valueOf("0");
							}
						}
						team.setBroker(broker);
						team.setBrokerClassification(brokerClass);
					}
				}

				// passar la jornada i guardar-la
				Object[] tdJornada = node.evaluateXPath(TEAMS_DAY_XPATH);
				for( Object jornadaContent: ((TagNode)tdJornada[1]).getChildren() )
				{
					Integer day = Integer.valueOf("0");
					try{
						day = Integer.valueOf(nf.parse(jornadaContent.toString().replace("Jornada ","").trim()).intValue());
					}catch(ParseException pe){
						day = Integer.valueOf("0");
					}
					team.setDay(day);
				}

				// guardem al llistat de teams
				teams.add(team);
			}
		}

		// parsejat ok
		Log.d(TAG, "MyTeamsParser: team list parsed ok");
		return teams;

	}
}
